/**
 * 
 */
package com.newtribe.security.kmc;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import com.newtribe.security.cert.KMCConfig;
import com.newtribe.security.util.FilePathUtil;

/**
 * @author newtribe
 *
 */
public class KeyPairManager {
	
	private KMCConfig kmc ;
	
    KeyStore keystore =KeyStore.getInstance("jks") ;


	/**
	 * @return the kmc
	 */
	public KMCConfig getKmc() {
		return kmc;
	}

	/**
	 * @param kmc the kmc to set
	 */
	public void setKmc(KMCConfig kmc) {
		this.kmc = kmc;
	}
	public KeyPairManager(KMCConfig kmc) throws Exception{
		this.kmc = kmc;
		init();
	}
	
    
	/**
	 * @return the pubkey
	 */
	public PublicKey getPubkey(String  alias) throws Exception{
		
		Certificate cert =getCertificate(alias) ;
		return cert.getPublicKey();
	}


	public X509Certificate getCertificate(String alias) throws Exception {
		
		X509Certificate cert  =(X509Certificate)keystore.getCertificate(alias) ;
	    return cert ;
		
	}
	
	/**
	 * @return the prikey
	 */
	public PrivateKey getPrikey(String alias)throws Exception {
		char[] password =kmc.getPasswd().toCharArray();
		PrivateKey prikey =(PrivateKey) keystore.getKey(alias, password) ;
		return prikey;
	}


	public PublicKey generatePrikey(String algo ,int keysize) throws Exception {
		KeyPairGenerator keygen = KeyPairGenerator.getInstance(algo);
	    SecureRandom secrand = new SecureRandom();
	    secrand.setSeed(System.currentTimeMillis()); 
	    keygen.initialize(keysize, secrand); 
        KeyPair keys = keygen.generateKeyPair(); 
        return keys.getPublic();
		
	}

	 void init() throws Exception{

		 
			String type =kmc.getType() ;
			if ("jks".equals(type))  {
				
	
		   File storeFile =new File(FilePathUtil.getUserDir() + kmc.getFile()) ;
		   
		     InputStream in =new FileInputStream (storeFile) ;
		     try {
				char[] password =kmc.getPasswd().toCharArray();
				 keystore.load(in ,password );
			} finally {
				if (in !=null )
				in.close();
			}
		     

		     // this.pubkey = keystore.getCertificate(kmc.get)
		    // this. prikey = keys.getPrivate();
	   
		     
			}
	    
		}
	
	 void store (KeyStore keystore ,String alias ,String passwd) throws Exception {
		
//		 keystore.setKeyEntry(alias, prikey, passwd.toCharArray(), null);
//		keystore.store(null, passwd.toCharArray());
		
	}

}
